import {Image, ScrollView, Video, Text, View} from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, {Component} from 'react';
import * as T from '../types';
import actions from '../actions/index';
import {connect} from 'react-redux';
import {store2Props} from '../selectors';
import api from 'api';
import 'taro-ui/dist/style/components/tabs.scss';
import './post.less';
import Blank from '@/pages/common/blank';
import {returnTime} from '@/utils/returnTime';
import userImg from '@/assets/image/community/user.png';
import write from '@/assets/image/community/write.png';
import zan from '@/assets/image/community/zan.png';
import zanCurr from '@/assets/image/community/zan-curr.png';
import share from '@/assets/image/community/share.png';
import nones from '@/assets/image/none/nones.png';
import Index from '../index';

type IPostProps = T.IProps & T.IPostProps;
//@ts-ignore
@connect<Partial<IPostProps>, T.IPostState>(store2Props, actions)
export default class post extends Component<Partial<IPostProps>, T.IPostState> {
  constructor(props) {
    super(props);
    this.state = {
      refresherTriggered: false,
      clickLikeVal: false,
    };
  }

  componentDidMount() {}

  //详情
  navPostDetail(item, type) {
    Taro.navigateTo({
      url: `/pages/package-B/community-detail/index?id=${item.id}&type=${type}`,
    });
  }

  renderItem(item, index, type) {
    let {
      actions: {action},
    } = this.props;
    return (
      <View
        className="postViews"
        onClick={(e) => {
          e.stopPropagation();
          if (Taro.getStorageSync('blacklistModel')) {
            action.commonChange('main.blacklistModel', true);
            return;
          }
          this.navPostDetail(item, false);
        }}
      >
        {item.videoImg && item.videoUrl ? (
          <View
            className="imgItem"
            onClick={() => {
              // this.setState({
              //   videoAddress: item.videoUrl,
              //   customVideoShow: true,
              // });
            }}
          >
            <Video
              className="video"
              src={item.videoUrl}
              initialTime={0}
              controls
              autoplay={false}
              loop={false}
              muted={false}
            />
          </View>
        ) : null}
        {item.url != '' && item.url ? this.renderImg(item.url.split(';')) : null}
        {item.content != '' && <Text className="title">{item.content}</Text>}
        <View className="userBox">
          <View className="row">
            <Image className="userImg" mode="aspectFill" src={item.userImg || userImg} />
            <View className="userName">{item.userName}</View>
          </View>
          <View
            className="row"
            onClick={(e) => {
              e.stopPropagation();
              if (Taro.getStorageSync('blacklistModel')) {
                action.commonChange('main.blacklistModel', true);
                return;
              }
              this.LikeClick(item, index, item.thumbFlag, type);
            }}
          >
            {item.thumbFlag ? (
              <Image className="b_icon" mode="widthFix" src={zan} />
            ) : (
              <Image className="b_icon" mode="widthFix" src={zanCurr} />
            )}
            <View className="thumbNum">{item.thumbNum}</View>
          </View>
        </View>
      </View>
    );
  }

  //图片渲染
  renderImg(list) {
    return (
      <View className="imgItem">
        <Image
          // onClick={this.onImageClick.bind(this, list[0], [list[0]])}
          src={list[0]}
          mode="widthFix"
          className="b_img"
        />
      </View>
    );
  }
  onImageClick = (item, urls) => {
    this.previewImage(item, urls);
  };
  previewImage = (img, files) => {
    Taro.previewImage({
      current: img, // 当前显示图片的http链接
      urls: files, // 需要预览的图片http链接列表
    });
  };

  //点赞、取消点赞
  async LikeClick(item, index, thumbFlag, type) {
    let {clickLikeVal} = this.state;
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    if (!itemStr) {
      Taro.navigateTo({
        url: '/pages/package-C/login/login/index',
      });
      return;
    } else {
      if (clickLikeVal) {
        return;
      }
      this.setState(
        {
          clickLikeVal: true,
        },
        () => {
          let {
            main: {leftData, rightData},
            actions: {action},
          } = this.props;
          if (thumbFlag) {
            //点赞后处理
            if (type == 1) {
              leftData[index].thumbFlag = !thumbFlag;
              leftData[index].thumbNum += 1;
              action.commonChange('main.leftData', leftData);
            } else {
              rightData[index].thumbFlag = !thumbFlag;
              rightData[index].thumbNum += 1;
              action.commonChange('main.rightData', rightData);
            }
          } else {
            //取消点赞后处理
            if (type == 1) {
              leftData[index].thumbFlag = !thumbFlag;
              leftData[index].thumbNum -= 1;
              action.commonChange('main.leftData', leftData);
            } else {
              rightData[index].thumbFlag = !thumbFlag;
              rightData[index].thumbNum -= 1;
              action.commonChange('main.rightData', rightData);
            }
          }
          let params = {
            userId: itemStr.user.id,
            targetId: item.id,
            type: 1,
          };
          if (thumbFlag) {
            //点赞
            action.addThumb(params);
          } else {
            //取消点赞
            action.deleteThumb(params);
          }
          this.setState({
            clickLikeVal: false,
          });
        },
      );
    }
  }

  _onScrollToLower = () => {
    let {
      main: {pageNum, totalPages},
      actions: {action},
    } = this.props;
    let num = pageNum + 1;
    if (pageNum == totalPages) return;
    this.props.actions.action.commonChange('main.pageNum', num);
    let {user} = Taro.getStorageSync('b2b-wechat@login');
    this.props.actions.action.page({
      size: 20,
      userId: user?.id || '',
    });
  };

  _onRefresherRefresh = () => {
    let {refresherTriggered} = this.state;
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });
    this.props.actions.action.commonChange('main.pageNum', 1);
    let {user} = Taro.getStorageSync('b2b-wechat@login');
    this.props.actions.action.page({
      size: 20,
      userId: user?.id || '',
    });
    setTimeout(() => {
      this.setState({
        refresherTriggered: false,
      });
    }, 2000);
  };

  render() {
    let {refresherTriggered} = this.state;
    let {
      main: {leftData, rightData, pageNum, totalPages, isLoading},
      actions: {action},
    } = this.props;

    return (
      <View className="communityPost">
        <ScrollView
          className="scrollView"
          onScrollToLower={this._onScrollToLower}
          refresherEnabled
          refresherTriggered={refresherTriggered}
          onRefresherPulling={this._onRefresherRefresh}
          scrollY
        >
          {leftData.length > 0 ? (
            <View className="flex">
              <View className="itemBox">
                {leftData.map((item, index) => {
                  return this.renderItem(item, index, 1);
                })}
              </View>
              <View className="itemBox">
                {rightData.map((item, index) => {
                  return this.renderItem(item, index, 2);
                })}
              </View>
            </View>
          ) : (
            <Blank
              content="还没有帖子信息！"
              img={nones}
              imgStyle={{width: '343rpx', height: '288rpx'}}
              textStyle={{
                fontSize: '28rpx',
                color: '#BFBFBF',
                textAlign: 'center',
                marginTop: '40rpx',
              }}
            />
          )}
          {leftData.length != 0 && pageNum != totalPages && <View className="status">加载中</View>}
          {!isLoading && leftData.length != 0 && pageNum == totalPages && <View className="status">已经到底了~</View>}
        </ScrollView>
      </View>
    );
  }
}
